﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using SpCop.Core.Model;
using SpCop.Model;

namespace SpCop.General.Files
{
    class DoNotOverwriteConfigFiles : RuleBase
    {
        private static readonly string[] FilesArray;
        private static readonly string[] IsapiFilesArray;
        private static readonly string[] ConfigFilesArray;
        private static readonly string[] AllFiles;

        static DoNotOverwriteConfigFiles()
        {
            GetFilesFromEmbededResource("SpCop.General.Files.bin.12.files", out FilesArray);
            GetFilesFromEmbededResource("SpCop.General.Files.isapi.12.files", out IsapiFilesArray);
            GetFilesFromEmbededResource("SpCop.General.Files.config.12.files", out ConfigFilesArray);
            AllFiles = IsapiFilesArray.Concat(ConfigFilesArray).Concat(FilesArray).ToArray();

        }

        public override IList<Problem> Check(Package package)
        {
            var items = base.Check(package);

          
           
            foreach (var rootFile in package.RootFiles)
            {

               // var data = ASCIIEncoding.UTF8.GetString(FileLists.bin_12).Split("\r\n".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);

                if (AllFiles.Contains(rootFile.ToUpperInvariant()))
                   AddProblem("OverwritingBuiltInFile", rootFile);


                if (rootFile.ToUpperInvariant() == "BIN\\OWSTIMER.EXE.CONFIG")
                   AddProblem("OverwritingOwsTimerFile", rootFile);

            }

            return items;
        }

        private static void GetFilesFromEmbededResource(string resourceName, out string[] target)
        {
            using (var dataStream = typeof(DoNotOverwriteConfigFiles).Assembly.GetManifestResourceStream(resourceName))
            {
                if (dataStream != null)
                    using (var textReader = new StreamReader(dataStream))
                    {
                        target = textReader
                            .ReadToEnd()
                            .Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                            .Select(a => a.ToUpperInvariant())
                            .ToArray();
                        return;
                    }
            }
            target = new string[0];
            return;
        }

        
    }
}
